import React from 'react'
import MyContext from './context'
class Provider extends React.Component{
  render(){
    let {children,store} = this.props;
    // children App组件
    return <MyContext.Provider value={{store}}>
      {children}
    </MyContext.Provider>
  }
}

const connect = function (mapStateToProps,mapDispatchToProps){
  return function(Com){
    return class Temp extends React.Component{
      static contextType = MyContext
      constructor(props,context){
        super(props,context)
        //  所有经过Connect处理过的组件 返回值都是临时创造的Temp
        // 这些Temp组件都可以通过 context 获取到  store属性
        console.log(props,context)
        this.state = mapStateToProps(context.store.getState());
      }
      componentDidMount(){
        this.cb = this.context.store.subscribe(()=>{
          this.setState(mapStateToProps(this.context.store.getState()))
        })
      }
      componentWillUnmount(){
        this.cb();
      }
      render() {
        return <Com 
          {...this.props}
          {...this.state} 
          {...mapDispatchToProps(this.context.store.dispatch)}/>
      }
    }
  }
}

export {Provider,connect}